package com.tool.payment.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component("paymentSpringContextHolder")
public class SpringContextHolder implements ApplicationContextAware,DisposableBean {

	private static ApplicationContext applicationContext = null;
	
	public static ApplicationContext getApplicationContext(){
		assertContextInjected();
		return applicationContext;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name){
		assertContextInjected();
		return (T)applicationContext.getBean(name);
	}
	
	public static <T> T getBean(Class<T> type){
		assertContextInjected();
		return applicationContext.getBean(type);
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextHolder.applicationContext = applicationContext;
	}

	@Override
	public void destroy() throws Exception {
		SpringContextHolder.clearHolder();
	}
	/**
	 * 清除applicationContext
	 */
	public static void clearHolder(){
		applicationContext = null;
	}
	
	private static void assertContextInjected(){
		if(applicationContext == null){
			throw new RuntimeException("applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
		}
	}
}
